import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as authActionCreator from '../../actions/auth-actions';
import * as constantActionCreator from '../../actions/constant-actions';
import * as intlActionCreator from '../../actions/intl-actions';
import * as orderActionCreator from '../../actions/order-actions';
import * as messageActionCreator from '../../actions/message-actions';
import LogoSvg from '../../resource/svg/logo.svg';
import {SvgCss} from 'react-native-svg';
import {getRealSize} from '../../utils';

class SplashScreen extends React.PureComponent {
  static navigationOptions = {
    header: null,
  };

  constructor() {
    super();
    this.state = {
      count: 3,
    };
  }

  componentDidMount() {
    const {authActions, constantActions, intlActions} = this.props;
    authActions.loadToken();
    authActions.loadDeviceInfo();
    authActions.loadLocation();
    constantActions.loadCategory();
    intlActions.load();
    this.countDownTimer = setInterval(this.interval, 1000);
  }

  interval = async () => {
    const {token, navigation} = this.props;
    this.setState({count: this.state.count - 1});
    if (this.state.count < 1) {
      this.setState({count: 0});
      clearInterval(this.countDownTimer);
      // this.props.navigation.navigate('Example');
      if (token.access) {
        navigation.replace('Main');
      } else {
        navigation.replace('Auth');
      }
    }
  };

  componentWillUnmount() {
    clearInterval(this.countDownTimer);
  }

  render() {
    // <Text style={{fontSize: 88}}>Molar</Text>
    return (
      <View
        style={{
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        <Text style={Styles.count}>{this.state.count}</Text>
        <SvgCss
          width={getRealSize(320)}
          height={getRealSize(88)}
          xml={LogoSvg}
        />
      </View>
    );
  }
}

const mapStateToProps = state => ({
  token: state.token,
  user: state.user,
});

const mapDispatchToProps = dispatch => ({
  authActions: bindActionCreators(authActionCreator, dispatch),
  constantActions: bindActionCreators(constantActionCreator, dispatch),
  intlActions: bindActionCreators(intlActionCreator, dispatch),
  orderActions: bindActionCreators(orderActionCreator, dispatch),
  messageActions: bindActionCreators(messageActionCreator, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(SplashScreen);

const Styles = StyleSheet.create({
  count: {
    position: 'absolute',
    top: 20,
    right: 20,
    color: '#e1e1e1',
  },
});
